<template>
  <div class="all">
    <div class="top">
      <el-row>
        <el-form ref="form" inline label-position="left">
          <el-col :span="3">
            <el-form-item label="编 码：">
              <el-input v-model="query.coding" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="账 号：">
              <el-input v-model="query.name" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="状 态：">
              <SelfSelect v-model="query.status" :show-list="adminStatus" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-button style="margin-top: 38%" icon="el-icon-search" type="primary" @click="index">查找</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <el-row class="btns">
        <el-button v-if="roles.includes('PersonnelStaffAdd')" type="primary" icon="el-icon-circle-plus-outline" @click="handleAdd">新增</el-button>
        <el-button type="primary" icon="el-icon-printer" @click="exportDialog">导出</el-button>
        <div v-if="roles.includes('PersonnelStaffImport')" class="buttonBox">
          <el-upload :show-file-list="false" action="" :before-upload="file => workbook(file)">
            <el-button type="primary" icon="el-icon-edit" size="mini">批量导入</el-button>
          </el-upload>
        </div>
        <el-button v-if="roles.includes('PersonnelStaffDelete')" type="danger" icon="el-icon-delete" @click="delBtn">删除</el-button>
        <el-button v-if="roles.includes('PersonnelStaffImport')" type="primary" icon="el-icon-download" @click="downloadExcel">下载模板</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="refresh">刷新</el-button>
      </el-row>
      <span class="total">总数：{{ total }}</span>
    </div>
    <div class="main">
      <div class="left">
        <el-tabs type="border-card" stretch style=" overflow: auto;height: 470px" @tab-click="handleClick">
          <el-tab-pane label="按分类">
            <el-input v-model="filterCategoryText" clearable size="small" style="margin-bottom: 10px" placeholder="请输入关键字进行过滤" />
            <el-tree ref="tree" :data="categoryTree" accordion :props="categoryProps" :expand-on-click-node="false" :filter-node-method="filterNode" @node-click="categoryClick" />
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="right">
        <el-table ref="multipleTable" v-loading="loading" border tooltip-effect="dark" width="100%" stripe height="90%" :data="dataList" @selection-change="handleSelectionChange">
          <el-table-column label="序号" type="index" align="center" width="50" />
          <el-table-column type="selection" align="center" width="55" />
          <el-table-column prop="coding" label="编号" align="center" width="100" />
          <el-table-column prop="name" label="账号" align="center" width="140" />
          <el-table-column prop="real_name" label="姓名" align="center" width="140" />
          <el-table-column label="状态" align="center">
            <template scope="{row}">
              <div v-html="row.status_table" />
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="电话" align="center" width="160" />
          <el-table-column prop="email" label="邮箱" align="center" width="160" />
          <el-table-column prop="department" label="部门" align="center" width="100" />
          <el-table-column prop="section" label="科室" align="center" width="100" />
          <el-table-column prop="classx" label="班组" align="center" width="120" />
          <el-table-column prop="job" label="岗位" align="center" width="100" />
          <el-table-column prop="profession" label="专业" align="center" width="120" />
          <el-table-column label="操作" fixed="right" width="300" align="center">
            <template scope="{row}">
              <el-button v-if="roles.includes('PersonnelStaffRole')" type="success" @click="goRole(row.id)">权限</el-button>
              <el-button v-if="roles.includes('PersonnelStaffPassword')" type="warning" @click="changePasswordDialog(row.id)">更改密码</el-button>
              <el-button v-if="roles.includes('PersonnelStaffDetail')" type="primary" @click="goDetail(row.id)">编辑</el-button>
              <el-button v-if="roles.includes('PersonnelStaffDelete')" type="danger" @click="handleDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="page" align="center" background :page-size="query.limit" layout="total,prev,pager,next,jumper" :total="total" :current-page.sync="query.page" @current-change="index" @size-change="index" />
      </div>
    </div>
    <el-dialog title="修改密码" :visible.sync="dialogPassword" style="width: 55%;margin: 0 auto">
      <el-form ref="passwordForm" key="password" :model="password" :rules="rulesA" label-width="120px">
        <el-col>
          <el-form-item label="密码：" prop="p1">
            <el-input v-model="password.p1" clearable style="width: 200px" />
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="确认密码：" prop="p2">
            <el-input v-model="password.p2" clearable style="width: 200px" />
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="passwordCancel">取 消</el-button>
        <el-button type="primary" @click="passwordSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="请选择导出字段" :visible.sync="excelDialog" width="60%">
      <div>
        <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;" />
        <el-checkbox-group v-model="needExport" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="title in tableHead" :key="title" class="checkStyle" :label="title" />
        </el-checkbox-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="excelDialog = false">取 消</el-button>
        <el-button type="primary" @click="exportExcel">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :show-close="false" :visible.sync="dialogVisible" title="修改权限">
      <el-form label-width="80px" label-position="left">
        <el-form-item>
          <el-tree
            ref="roleTree"
            :check-strictly="checkStrictly"
            :data="roleTree"
            :props="roleProps"
            show-checkbox
            node-key="id"
            style="width: 30vw"
            :default-checked-keys="defaultChecked"
            class="permission-tree"
            @check-change="handleCheckChange"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="primary" @click="cancelRole">取消</el-button>
        <el-button type="success" @click="confirmRole">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SelfSelect from '@/components/select-o'
import API from '@/api/personnel/admin'
import TREE from '@/api/role/role'
import { adminTables } from '@/utils/Table'
import { knowledgeType, adminStatus } from '@/utils/option'
import XLSX from 'xlsx'
import { mapGetters } from 'vuex'
const tableOptions = ['编号', '账号', '姓名', '电话', '邮箱', '部门', '科室', '班组', '岗位', '工程师', '专业', '状态', '排序']
export default {
  inject: ['goUrl', 'reload'],
  components: {
    SelfSelect
  },
  data() {
    return {
      categoryTree: [],
      dataList: [],
      total: 0,
      loading: true,
      query: {
        limit: 15,
        page: 1
      },
      rulesA: {
        p1: { required: true, message: '请输入密码', trigger: 'change' },
        p2: { required: true, message: '请输入确认密码', trigger: 'change' }
      },
      password: {
        p1: '',
        p2: '',
        id: ''
      },
      filterCategoryText: '',
      knowledgeType,
      adminStatus,
      categoryProps: {
        children: 'children',
        label: 'name'
      },
      defaultChecked: [],
      checkedNodes: [],
      checkStrictly: false,
      dialogPassword: false,
      multipleSelection: [],
      roleTree: null,
      admin_id: null,
      role: null,
      dialogVisible: null,
      adminTables,
      excelDialog: false,
      roleProps: {
        children: 'children',
        label: 'name'
      },
      exportList: [],
      needExport: ['编号', '账号', '姓名', '电话', '邮箱', '部门', '科室', '班组', '岗位', '工程师', '专业', '状态', '排序'],
      isIndeterminate: true,
      tableHead: tableOptions,
      checkAll: true
    }
  },
  created() {
    const query = JSON.parse(sessionStorage.getItem('query'))
    if (query) {
      this.query = query
      sessionStorage.removeItem('query')
    }
    this.index()
    API.tree().then(res => {
      this.categoryTree = res.data
    })
    window.addEventListener('keydown', this.handKeyCode, true)
  },
  computed: {
    ...mapGetters(['roles']),
    pages() {
      return this.total / 300 + 1
    }
  },
  watch: {
    filterCategoryText(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    index() {
      this.loading = true
      API.getList(this.query).then(res => {
        this.dataList = res.data.data
        this.total = res.data.total
      }).finally(() => {
        this.loading = false
      })
      TREE.getList().then(res => {
        this.roleTree = res.data.data
      })
    },
    setStorage() {
      sessionStorage.setItem('query', JSON.stringify(this.query))
    },
    handKeyCode(e) {
      if (e.keyCode === 13 || e.keyCode === 32) { // 回车搜索
        this.index()
      }
    },
    goDetail(id) {
      this.setStorage()
      const url = `/personnel/staff/edit/${id}`
      this.goUrl(url)
    },
    handleAdd() {
      this.setStorage()
      this.goUrl('/personnel/staff/add')
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleClick(tab, event) {
      console.log(tab)
    },
    refresh() {
      this.reload()
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        API.delete(id).then(res => {
          if (res.data.error_code !== 1) {
            this.$message.error(res.data.message)
          } else {
            this.$message.success('删除成功')
            this.setStorage()
            this.index()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    changePasswordDialog(id) {
      console.log(id)
      this.password.id = id
      this.dialogPassword = true
    },
    passwordCancel() {
      this.password.id = ''
      this.password.p1 = ''
      this.password.p2 = ''
      this.dialogPassword = false
    },
    passwordSubmit() {
      API.changePassword(this.password).then(res => {
        if (res.data.error_code !== 1) {
          this.$message.error(res.data.message)
        } else {
          this.$message.success('修改成功')
          this.passwordCancel()
        }
      })
    },
    categoryClick(v) {
      this.query.category_id = v.id
      this.index()
    },
    filterNode(value, data) {
      console.log(data)
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    goRole(id) {
      this.dialogVisible = true
      this.admin_id = id
      API.getOne(id).then(res => {
        this.defaultChecked = res.data.role_list
      })
    },
    resetChecked() {
      this.$nextTick(() => {
        this.$refs.roleTree.setCheckedKeys([])
      })
    },
    handleCheckChange() {
      this.checkedKeys = this.$refs.roleTree.getHalfCheckedKeys()
      this.checkedNodes = this.$refs.roleTree.getCheckedNodes()
      console.log(this.checkedNodes)
    },
    cancelRole() {
      this.dialogVisible = false
      this.resetChecked()
    },
    confirmRole() {
      if (this.checkedNodes) {
        const arr = []
        this.checkedNodes.forEach(item => {
          const id = item.id
          arr.push(id)
        })
        this.role = arr
      }
      const roleData = {
        admin_id: this.admin_id,
        role: this.role
      }
      API.append(roleData).then(res => {
        if (res.data.error_code === 1) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
        } else {
          this.$message.error(res.data.message)
        }
      })
      this.dialogVisible = false
      this.resetChecked()
      console.log('权限确定')
    },
    delBtn() {
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        const idArray = []
        this.multipleSelection.forEach(item => {
          idArray.push(item.id)
        })
        const id = idArray.join(',')
        this.handleDel(id)
      } else {
        this.$message('请先选择，然后再删除')
      }
    },
    downloadExcel() {
      const a = document.createElement('a')
      a.href = 'https://d.ubeiyun.com/xls/人员台账.xlsx'
      a.download = '备件模板.xlsx'
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    workbook(file) {
      this.loading = true
      const reader = new FileReader()
      const self = this
      reader.onload = function(e) {
        let outData = []
        const data = e.target.result
        const workbook = XLSX.read(data, { type: 'binary' })
        const sheetNames = workbook.SheetNames
        sheetNames.forEach(() => {
          outData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
        })
        const postData = {}
        postData.outData = outData
        API.excel(postData).then(response => {
          if (response.data.error_code === 1) {
            self.$message.success(`恭喜你，操作成功`)
            self.loading = false
            self.index()
          } else {
            self.$message.error(response.data.message)
            self.loading = false
            self.index()
          }
        }).finally(() => {
          self.loading = false
        })
      }
      reader.readAsBinaryString(file)
      return false
    },
    exportDialog() {
      this.excelDialog = true
    },
    handleCheckAllChange(val) {
      this.needExport = val ? tableOptions : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      const checkedCount = value.length
      this.checkAll = checkedCount === this.tableHead.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.tableHead.length
    },
    toExcel() {
      const exportData = []
      const exportTitle = []
      const titleObj = this.adminTables
      exportData.push(this.needExport)
      for (const keys of this.needExport) {
        exportTitle.push(Object.keys(titleObj).find(key => titleObj[key] === keys))
      }
      this.exportList.forEach(item => {
        const arr = []
        for (const key of exportTitle) {
          arr.push(item[key])
        }
        exportData.push(arr)
      })
      const ws = XLSX.utils.aoa_to_sheet(exportData)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      /* save to file */
      XLSX.writeFile(wb, '人员台账.xlsx')
      this.refresh()
      this.loading = false
    },
    async getExcel(condition) {
      const res = await API.getList(condition)
      const exportList = res.data.data
      this.exportList.push(...exportList)
      this.loadingExcel = '正在导出' + this.exportList.length
      if (this.exportList.length === this.total) {
        this.toExcel()
        this.isLoading = false
      }
    },
    allExcel() {
      this.isLoading = true
      const arr = Object.keys(this.query)
      const len = arr.length
      if (len > 2) {
        const condition = this.query
        condition.limit = this.total
        condition.page = 1
        this.getExcel(condition)
      } else {
        for (let i = 1; i <= this.pages; i++) {
          const condition = {
            limit: 300,
            page: i
          }
          this.getExcel(condition)
        }
      }
    },
    exportExcel() {
      this.loading = true
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        this.exportList = this.multipleSelection
        this.toExcel()
      } else {
        this.allExcel()
      }
    }
  }
}
</script>
